package com.lagou.cluster.config;

import com.lagou.cluster.service.ItstyleProcessor;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RPriorityQueue;
import org.redisson.api.RQueue;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.scheduler.Scheduler;

import java.util.Arrays;

@Configuration
public class RedissonConfig {
    @Value("${org.redisson.nodes}")
    private String nodes;

    @Bean
    RedissonClient client() {
        Config config = new Config();
        ClusterServersConfig tmp = config.useClusterServers();
        for (String str : StringUtils.split(nodes, ",")) {
            tmp.addNodeAddress("redis://" + str);
        }
        return Redisson.create(config);
    }

    Scheduler scheduler(String site) {
        RedissonClient cli = client();
        RQueue<Request> queue = cli.getQueue("queue_" + site);
        return new RedissonScheduler(queue, cli.getSet("set_" + site));
    }

    @Bean
    Spider qqMusicSpider(ItstyleProcessor processor) {
        return Spider.create(processor)
                .addUrl("https://blog.52itstyle.vip")
                .setScheduler(scheduler("52itstyle"));
    }

}
